﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Data;
using System.Data.SqlClient;
using ResponseObject;
using BartonExtension;
using SqlServerWrapper;

namespace WebSrvs.NET.Handler
{
    /// <summary>
    /// ZK_UserUploaderHandler 的摘要描述
    /// </summary>
    public class ZK_UserShareHandler : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            ZKResponse response = new ZKResponse();
            try
            {
                int uid = context.Request["uid"].toInt32().Value;
                string userSay = context.Request["userSay"].ToString();
                HttpPostedFile file = context.Request.Files["Filedata"];
                if (file == null)
                {
                    response.isProcessSuccess = false;
                    response.errMsg = "请选择上传图片";
                    context.Response.Write(response.ToJson());
                    return;
                }
                DateTime now = DateTime.Now;
                string filename = now.DateTimeFileName() + ".png";
                string path = context.Server.MapPath("../data/images/user_shares/{0}/".FormatWith(uid));
                if (!Directory.Exists(path))
                    Directory.CreateDirectory(path);
                path = path + filename;
                file.SaveAs(path);

                string connStr = SqlConnectionManager.GetConnStrFromConfig();
                using (SqlConnection conn = SqlConnectionManager.CreateSqlConnection(connStr))
                {
                    conn.Open();
                    using (SqlCommand cmd = SqlCommandManager.Create(conn, System.Data.CommandType.StoredProcedure))
                    {
                        cmd.CommandText = "proc_add_user_share";
                        cmd.Parameters.Add("@uid", SqlDbType.Int).Value = uid;
                        cmd.Parameters.Add("@userSay", SqlDbType.VarChar).Value = userSay;
                        cmd.Parameters.Add("@image", SqlDbType.VarChar).Value = filename;
                        cmd.Parameters.Add("@timetag", SqlDbType.Int).Value = now.DateTimeFileName().toInt32().Value;
                        cmd.ExecuteNonQuery();
                    }
                }
            }
            catch(Exception ex)
            {
                response.isProcessSuccess = false;
                response.errCode = ErrorCodes.CODE_ERR_INTERNAL_ERR;
                response.errMsg = ex.Message;
            }
            context.Response.Write(response.ToJson());
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}